#include "GapStateRegisterPend.h"
#include "GapStateMap.h"
#include "GAP.pb.h"
#include "Trace.h"

namespace tsc
{
namespace mgw
{

using namespace GatewayApplicationPart;
using namespace ProtocolsCommon;
using namespace tsc::common;

/*******************************************************************************
 *
 * Constructor
 *
 ******************************************************************************/
GapStateRegisterPend::GapStateRegisterPend() :
	GapStateBase("RegisterPend")
{

} // GapStateRegisterPend::GapStateRegisterPend

/*******************************************************************************
 *
 * Destructor
 *
 ******************************************************************************/
GapStateRegisterPend::~GapStateRegisterPend()
{

} // GapStateRegisterPend::~GapStateRegisterPend

//===================================================================
GapStateRegisterPend* GapStateRegisterPend::instance()
{
	static GapStateRegisterPend mInstance;
	return &mInstance;
}

//===================================================================
void
GapStateRegisterPend::handleEventGapConnectRej(
    GapGenerator* gapGen,
    GapEventConnectRej* event,
    EventData*& eventData)
{
    TRACE(3, STR("Received GapConnectRej - will try again in %u[ms]",
                 T_711_VALUE));
    gapGen->cancelT709();
    gapGen->startT711();
    gapGen->changeState(GapStateMap::mpStateUnregistered);

    EventData::deleteEvent(eventData);
}

//===================================================================
void
GapStateRegisterPend::handleEventGapConnectCfm(
    GapGenerator* gapGen,
    GapEventConnectCfm* event,
    EventData*& eventData)
{
    TRACE(3,
      STR("Received GapConnectCfm, mgwId=0x%x(%u) - connection established",
          event->getMgwId(), event->getMgwId()));

    gapGen->cancelT709();
    gapGen->setMgwId(event->getMgwId());

    gapGen->changeState(GapStateMap::mpStateRegistered);

    EventData::deleteEvent(eventData);
}

//===================================================================
void
GapStateRegisterPend::handleEventGapT709Expired(
    GapGenerator* gapGen,
    GapEventT709Expired* event,
    EventData*& eventData)
{
    TRACE(3, STR("Timeout waiting for GapConnectCfm - will try "
                 "to establish connection again in %u[ms]",
                 T_711_VALUE));

    gapGen->startT711();
    gapGen->changeState(GapStateMap::mpStateUnregistered);

    EventData::deleteEvent(eventData);
}


} // namespace mgw
} // namespace tsc
